/*
 * FileManager.cpp
 *
 *  Created on: 7 июн. 2022 г.
 *      Author: nikita
 */

#include "FileManager.h"

namespace STC_calc
{

void StringFile::read_all()
{
	std::shared_ptr<string_list> temp;
	std::ifstream in(file_name);
	std::string str;
	if (!in.is_open()) throw(RuntimeErrorClass("Error: file has not opened"));
	while(!in.eof())
	{
		getline(in, str);
		temp->push_back(str);
	}
	buffer->resize(temp->size());
	int i = 0;
	for (auto a : *temp)
	{
		i++;
		(*buffer)[i] = a;
	}
	in.close();
}

void StringFile::write_all()
{
	std::ofstream out(file_name);
	for (auto a : *buffer)
	{
		out << a;
	}
}

StringFile::StringFile(const std::string& file_name, const std::fstream::openmode openmode):
		file_name(file_name), mode(openmode)
{
	pos = 0;
	try{
		std::fstream file(file_name, openmode);
		if (file.is_open()) throw(RuntimeErrorClass("Error: file has not opened"));
		file.close();
		if (mode == std::fstream::openmode::_S_out) read_all();
	}
	catch(const RuntimeErrorClass& e)
	{
		throw(e);
	}
	catch(const std::exception& e)
	{
		throw(RuntimeErrorClass(e.what()));
	}
}
StringFile::~StringFile()
{
	if (mode != std::fstream::in) write_all();
}

void StringFile::write(const std::string& str)
{
	buffer->push_back(str);
	pos++;
}

std::shared_ptr<string_vector> FileManager::load_args(const std::string& file_name)
{
	StringFile a(file_name, std::fstream::in);
	return a.get_buffer();
}
std::shared_ptr<string_vector> FileManager::load_configs(const std::string& file_name)
{
	std::string str = file_name;
	if (file_name == "~default") str = "default.conf";

	try
	{
		StringFile a(str, std::fstream::in);
		return a.get_buffer();
	}
	catch(const RuntimeErrorClass& e)
	{
		std::shared_ptr<string_vector> ret = std::make_shared<string_vector>(1);
		(*ret)[0] = "~default";
		Logger::put("Error. Config file haven't found. Using default");
		return ret;
	}
}

static std::shared_ptr<string_vector> load_help_text(const std::string& file_name)
{

	try
	{
		StringFile a(file_name, std::fstream::in);
		return a.get_buffer();
	}
	catch(const RuntimeErrorClass& e)
	{
		std::shared_ptr<string_vector> ret = std::make_shared<string_vector>(1);
		(*ret)[0] = "~default";
		Logger::put("Error. help file haven't found. Using default");
		return ret;
	}
}

void FileManager::save_result(const long double& result, const std::string& file_name)
{
	std::string str = file_name;
	if (str == "~default") str = "default.out";

	StringFile a(str, std::fstream::out);
	a.write(std::to_string(result));
}
void FileManager::save_log(const std::string& log, const std::string& file_name)
{
	std::string str = file_name;
	if (str == "~default") str = "default.log";

	StringFile a(str, std::fstream::out);
	a.write(log);

}

} /* namespace STC_calc */
